<template>
  <div>
    <el-dialog
      v-model="visible"
      :title="!dataForm.seckillId ? $t('seckill.newAdd') : $t('seckill.view')"
      :close-on-click-modal="false"
      width="60%"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :disabled="true"
        :label-width="$t('language') === 'language' ? '180px' : '80px'"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-form-item
          :label="$t('seckill.activityName')"
          prop="seckillName"
        >
          <el-input
            v-model="dataForm.seckillName"
            style="max-width: 460px;"
            :disabled="!!dataForm.seckillId"
          />
        </el-form-item>
        <el-form-item
          :label="$t('seckill.activityTimeRange')"
          prop="dateRange"
        >
          <el-date-picker
            v-model="dataForm.dateRange"
            type="datetimerange"
            :range-separator="$t('coupon.to')"
            value-format="YYYY-MM-DD HH:mm:ss"
            :start-placeholder="$t('date.start')"
            :end-placeholder="$t('date.end')"
            :disabled="!!dataForm.seckillId"
            style="max-width: 460px;"
          />
        </el-form-item>
        <el-form-item
          :label="$t('seckill.purchaseLimitPerPerson')"
          prop="maxNum"
        >
          <el-checkbox
            v-model="dataForm.hasMaxNum"
            :disabled="!!dataForm.seckillId"
            @click="handlerChangeMaxNum"
          >
            {{ $t('seckill.openPurchaseLimit') }}
          </el-checkbox>
          <span v-show="dataForm.hasMaxNum">
            {{ $t('seckill.canBePurcPer') }}
            <el-input-number
              v-model="dataForm.maxNum"
              controls-position="right"
              :min="1"
              :max="1000"
              style="width:100px"
              :disabled="!!dataForm.seckillId"
            />
            {{ $t('seckill.item') }}
          </span>
        </el-form-item>
        <el-form-item
          :label="$t('seckill.orderCancel')"
          prop="maxCancelTime"
        >
          {{ $t('seckill.buyer') }}
          <el-input-number
            v-model="dataForm.maxCancelTime"
            :min="2"
            :max="15"
            controls-position="right"
            style="width:100px"
            :disabled="!!dataForm.seckillId"
          />
          {{ $t('seckill.buyerCancelTips') }}
        </el-form-item>
        <el-form-item :label="$t('seckill.commodity')">
          <el-button
            v-if="!dataForm.seckillId"
            plain
            style="float:left"
            @click="prodsSelectHandle()"
          >
            {{ $t('coupon.selectGoods') }}
          </el-button>
          <el-alert
            style="width: auto;display: inline-flex;"
            :title="$t('seckill.alertSeckillTips')"
            type="warning"
            :closable="false"
            show-icon
          />
        </el-form-item>
        <el-form-item>
          <el-card
            v-if="prod != null"
            :body-style="{ padding: '0px' }"
            style="height: 160px;width: 120px"
          >
            <prod-pic
              height="104px"
              width="100%"
              :pic="prod.pic"
            />
            <div class="card-prod-bottom">
              <span class="card-prod-name">{{ prod.prodName }}</span>
              <el-button
                v-if="prod.status === -1"
                type="text"
                class="card-prod-name-button"
                @click="deleteProd"
              >
                {{ $t('seckill.productHasBeenDeleted') }}
              </el-button>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item v-if="skuList.length">
          <el-table
            :data="skuList"
            header-cell-class-name="table-header"
            row-class-name="table-row"
          >
            <el-table-column
              prop="prodName"
              :label="$t('product.prodName')"
              width="320"
            >
              <template #default="scope">
                {{ scope.row.prodName }}
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              :label="$t('seckill.eventPrice')"
              :width="$t('language') === 'language' ? '241' : '201'"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.seckillPrice"
                  :precision="2"
                  :step="0.01"
                  :min="0.01"
                  :max="!!(!scope.row.status || dataForm.seckillId)?100000000:scope.row.price"
                  :disabled="!!(!scope.row.status || dataForm.seckillId)"
                />
                <div>{{ $t('seckill.skuPrice') }} {{ scope.row.price }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="stocks"
              :label="$t('seckill.activeInventory')"
              width="201"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.seckillStocks"
                  type="number"
                  :min="0"
                  :disabled="!!(!scope.row.status || dataForm.seckillId)"
                />
                <div>{{ $t('seckill.skuInventory') }} {{ scope.row.stocks }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('publics.status')">
              <template #default="scope">
                <el-button
                  v-if="scope.row.seckillPrice"
                  type="text"
                >
                  {{ $t('groups.startUsing') }}
                </el-button>
                <el-button
                  v-else
                  type="text"
                >
                  {{ $t('publics.disable') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            type="primary"
            @click="visible = false"
          >{{ $t('coupon.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :is-single="true"
      :prod-type="0"
      @refresh-select-prods="selectSeckillProd"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])
const dataRule = {
  startTime: [
    { required: true, message: '时间不可为空', trigger: 'blur' }
  ],
  seckillName: [
    { required: true, message: '活动名称不可为空', trigger: 'blur' }
  ],
  maxCancelTime: [
    { required: true, message: '订单取消时间不可为空', trigger: 'blur' }
  ]
}

const visible = ref(false)
const prod = ref(null)
const dataForm = ref({
  dateRange: [],
  seckillId: null,
  seckillName: null,
  startTime: null,
  endTime: null,
  seckillTag: null,
  maxNum: 1,
  hasMaxNum: false,
  maxCancelTime: 2
})
const skuList = ref([])
const dataFormRef = ref(null)
const init = (seckillId) => {
  dataForm.value.seckillId = seckillId || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    prod.value = null
    skuList.value = []
    if (dataForm.value.seckillId) {
      http({
        url: http.adornUrl('/platform/seckill/info/' + dataForm.value.seckillId),
        method: 'get',
        params: http.adornParams()
      })
        .then(({ data }) => {
          data.seckill.dateRange = [data.seckill.startTime, data.seckill.endTime]
          dataForm.value = data.seckill
          dataForm.value.hasMaxNum = data.seckill.maxNum > 0
          prod.value = data.prod
          getSkuList(data.prod.prodId, data.seckillSkus)
        })
    }
  })
}
defineExpose({ init })

const getSkuList = (prodId, seckillSkus) => {
  http({
    url: http.adornUrl('/platform/sku/getAllSkuList'),
    method: 'get',
    params: http.adornParams({
      prodId
    })
  })
    .then(({ data }) => {
      if (seckillSkus) {
        data.forEach(sku => {
          seckillSkus.forEach(seckillSku => {
            if (sku.skuId === seckillSku.skuId) {
              sku.seckillStocks = seckillSku.seckillStocks
              sku.seckillPrice = seckillSku.seckillPrice
            }
          })
        })
      }
      skuList.value = data
    })
}

/**
 * 表单提交
 */
const onSubmit = () => {
  // 秒杀不能更新
  if (dataForm.value.seckillId) {
    visible.value = false
    return
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (!prod.value) {
        ElMessage({
          message: '请选择活动商品',
          type: 'error'
        })
        return
      }
      if (!dataForm.value.hasMaxNum) {
        dataForm.value.maxNum = -1
      }
      dataForm.value.startTime = dataForm.value.dateRange[0]
      dataForm.value.endTime = dataForm.value.dateRange[1]
      dataForm.value.prodId = prod.value.prodId
      dataForm.value.seckillSkus = skuList.value.filter(sku => sku.status)

      http({
        url: http.adornUrl('/seckill/seckill'),
        method: 'post',
        data: http.adornData(dataForm.value)
      })
        .then(() => {
          ElMessage({
            message: $t('remindPop.success'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList')
            }
          })
        })
    }
  })
}

const prodsSelectVisible = ref(false)
const prodsSelectRef = ref(null)
/**
 * 显示添加指定商品弹框
 */
const prodsSelectHandle = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value?.init(dataFormRef.value?.discountProds)
  })
}

const handlerChangeMaxNum = (val) => {
  if (val) {
    dataForm.value.maxNum = 1
  } else {
    dataForm.value.maxNum = -1
  }
}

/**
 * 添加指定商品
 * @param prods
 */
const selectSeckillProd = (prods) => {
  if (prods) {
    prod.value = prods[0]
    getSkuList.value(prods[0].prodId)
  }
}

const deleteProd = () => {
  prod.value = null
  skuList.value = []
}
</script>
